package com.new2i.util;
  
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest; 

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
  
/**
 * 
 * xml 读写工具类
 * @since 2015/08/25
 * @author 2i
 *
 */
public class XmlUtil {

	
	/**
	 * 解析request流中的xml信息,转化为HashMap
	 * 
	 * @since 2015/08/25
	 * @author 2i
	 * @param request
	 * @return 
	 */
    @SuppressWarnings("unchecked")
	public static HashMap<String, String> parseXml(HttpServletRequest request) {  
    	HashMap<String, String> rHashMap = new HashMap<String,String>(); 
        InputStream inputStream;
		try {
			inputStream = request.getInputStream();
	        SAXReader reader = new SAXReader();   
	        Document document = reader.read(inputStream);   
	        Element root = document.getRootElement();   
	        List<Element> elementList = root.elements();   
	        for (Element e : elementList)  
	        	rHashMap.put(e.getName(), e.getText());   
	        inputStream.close(); 
	        inputStream = null;  
		} catch (Exception e1) {	 
	        inputStream = null;  
			System.out.println(e1.getLocalizedMessage());
		}   
		return rHashMap;
    }
     
    /**
	 * 解析xml字符串,转化为HashMap
	 * 
	 * @since 2015/08/28
	 * @author 2i
	 * @param request
	 * @return 
	 */
    @SuppressWarnings("unchecked")
    public static HashMap<String, String> parseXml(String xmlString) {  
    	HashMap<String, String> rHashMap = new HashMap<String,String>();  
		try {  
	        Document document = DocumentHelper.parseText(xmlString);  
	        Element root = document.getRootElement();   
	        List<Element> elementList = root.elements();   
	        for (Element e : elementList)  
	        	rHashMap.put(e.getName(), e.getText());    
		} catch (Exception e1) {	 
			System.out.println(e1.getLocalizedMessage());
		}   
		return rHashMap;
    }
    
    /**
   	 * 解析xml字符串,转化为HashMap
   	 * 
   	 * @since 2015/09/22
   	 * @author 2i
   	 * @param request
   	 * @return 
   	 */
	@SuppressWarnings("unchecked")  
	public static List<HashMap<String, String>> parseXmlByFile(String path) {
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); 
		try {
			InputStream inputStream = new FileInputStream(path);
			SAXReader reader = new SAXReader();
			Document document = reader.read(inputStream);
			// Document document = DocumentHelper.parseText(xmlString);
			Element root = document.getRootElement(); 
			List<Element> elementList = root.elements(); 
			for (Element e : elementList) { 
				List<Element> nodeList = e.elements();  
				HashMap<String, String> rHashMap = new HashMap<String,String>();  
				if(nodeList == null) { //若不存在子节点，把当前节点的信息保存
					rHashMap.put(e.getName(), e.getText());
					continue;
				}
				//存在子节点，将子节点的放入list
				for(Element node : nodeList) {  
					rHashMap.put(node.getName(), node.getText()); 
				}
				list.add(rHashMap); 
			}
		} catch (Exception e1) {
			System.out.println(e1.getLocalizedMessage());
		}
		return list;
	}
	
    /**
     * 生成xml字符串
     * @since 2015/08/26
     * @author 2i
     * @param nodeNames
     * @param nodeHashMap
     * @return
     */
    public static String generateXml(String[] nodeKeys,HashMap<String, ?> nodeHashMap){
    	String rXmlStr = ""; 
        Document document = DocumentHelper.createDocument();  
        Element rootElement = document.addElement("xml");    
		for(String node : nodeKeys) { 
			String nodeValue = (!nodeHashMap.containsKey(node) || nodeHashMap.get(node) == null)? "": nodeHashMap.get(node).toString();
	        rootElement.addElement(node).addText(nodeValue);   
		} 
		rXmlStr = rootElement.asXML();
		return rXmlStr; 
    }
 
    /**
     * 生成微信客服xml消息
     * @since 2015/08/25
     * @author 2i 
     * @param nodeHashMap
     * @return
     */
    public static String generateWeixinServiceMessageXml(HashMap<String, String> nodeHashMap){
    	String[] nodeNames = new String[]{"FromUserName","ToUserName","MsgType","Content","CreateTime"};
    	String fromUserName = nodeHashMap.get("FromUserName").toString();
    	String toUserName = nodeHashMap.get("ToUserName").toString();
    	nodeHashMap.put("FromUserName", toUserName);
    	nodeHashMap.put("ToUserName", fromUserName);
    	nodeHashMap.put("MsgType", "transfer_customer_service");
    	nodeHashMap.put("CreateTime", String.valueOf(System.currentTimeMillis()));
    	return generateXml(nodeNames, nodeHashMap);
    }
    
    /**
     * 生成图文消息
     * 
     * @author 2i
     * @since 2015/09/06
     * @param hashMap
     * @param aList
     * @return
     */
	public static String geneArticlesXml(HashMap<String, String> hashMap, ArrayList<HashMap<String, Object>> aList) {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("xml");
		root.addElement("ToUserName").addText(hashMap.get("FromUserName"));
		root.addElement("FromUserName").addText(hashMap.get("ToUserName"));
		root.addElement("CreateTime").addText(System.currentTimeMillis() + "");
		root.addElement("MsgType").addText("news");
		root.addElement("ArticleCount").addText(aList.size() + "");
		Element articles = root.addElement("Articles");
		for (int i = 0; i < aList.size(); i++) {
			Element item = articles.addElement("item");
			HashMap<String, Object> map = aList.get(i);
			item.addElement("Title").addText(map.get("title").toString());
			item.addElement("Description").addText(map.get("description").toString());
			item.addElement("PicUrl").addText(map.get("picUrl").toString());
			item.addElement("Url").addText(map.get("url").toString());
		}
		String xmlValue = root.asXML();
		return xmlValue;
	}
}
